//给你二叉树的根节点 root ，返回其节点值的 锯齿形层序遍历 。（即先从左往右，再从右往左进行下一层遍历，以此类推，层与层之间交替进行）。 
//
// 
//
// 示例 1： 
// 
// 
//输入：root = [3,9,20,null,null,15,7]
//输出：[[3],[20,9],[15,7]]
// 
//
// 示例 2： 
//
// 
//输入：root = [1]
//输出：[[1]]
// 
//
// 示例 3： 
//
// 
//输入：root = []
//输出：[]
// 
//
// 
//
// 提示： 
//
// 
// 树中节点数目在范围 [0, 2000] 内 
// -100 <= Node.val <= 100 
// 
//
// Related Topics 树 广度优先搜索 二叉树 👍 727 👎 0

package leetcode.editor.cn;

import com.gule.gl.leetcode.editor.cn.definition.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Queue;

//Java：二叉树的锯齿形层序遍历
public class P103BinaryTreeZigzagLevelOrderTraversal{
    public static void main(String[] args) {
        TreeNode left1 = new TreeNode(2);
        TreeNode le2= new TreeNode(3);
        TreeNode r1 = new TreeNode(3);
        TreeNode r2 = new TreeNode(4);
        TreeNode root = new TreeNode(0);
        root.setLeft(left1);
        root.setRight(r1);
        left1.setLeft(le2);
        left1.setRight(r2);
        r2.setRight(r1);
        r2.setLeft(left1);

        Solution solution = new P103BinaryTreeZigzagLevelOrderTraversal().new Solution();
        // TO TEST
        List<List<Integer>> lists = solution.zigzagLevelOrder(root);
        System.out.println(lists.toArray());
    }
    //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if(Objects.isNull(root)){
            return new ArrayList<>();
        }
        List<List<Integer>> resList = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        boolean isOrderLeft = false;
        while(queue.size() > 0){
            LinkedList<Integer> levelList = new LinkedList<>();
            int size = queue.size();
            for(int i=0;i<size;i++){
                TreeNode poll = queue.poll();
                if(isOrderLeft){
                    levelList.addLast(poll.val);
                }else{
                    levelList.addFirst(poll.val);
                }
                if(Objects.nonNull(poll.right)){
                    queue.offer(poll.right);
                }
                if(Objects.nonNull(poll.left)){
                    queue.offer(poll.left);
                }
            }
            isOrderLeft = !isOrderLeft;
            resList.add(levelList);
        }
        return resList;
    }
}

//leetcode submit region end(Prohibit modification and deletion)

}
